<template>
  <div class="page-prod-list">
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="shopName"
            :label="$t('prodList.shopName') + ':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.shopName"
              type="text"
              clearable
              :placeholder="$t('prodList.shopName')"
            />
          </el-form-item>
          <el-form-item
            prop="keyword"
            :label="$t('product.prodName') + ':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.keyword"
              type="text"
              clearable
              :placeholder="$t('product.prodName')"
            />
          </el-form-item>
          <!-- <el-form-item prop="isCompose" :label="$t('product.comProd') + ':'">
            <el-select v-model="searchForm.isCompose" :placeholder="$t('product.comProd')">
              <el-option :label="$t('publics.no')" :value="0"></el-option>
              <el-option :label="$t('publics.yes')" :value="1"></el-option>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item
            prop="isCompose"
            :label="$t('product.prodMold') + ':'"
          >
            <el-select
              v-model="searchForm.mold"
              clearable
              :placeholder="$t('product.prodMold')"
            >
              <el-option
                :label="$t('product.physicalGoods')"
                :value="0"
              />
              <el-option
                :label="$t('product.virtualGoods')"
                :value="1"
              />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item
            prop="prodType"
            :label="$t('product.prodType')+ ':'"
          >
            <el-select
              v-model="searchForm.prodType"
              clearable
              :placeholder="$t('product.prodType')"
            >
              <el-option
                :label="$t('product.ordProd')"
                :value="0"
              />
              <el-option
                :label="$t('product.groupProd')"
                :value="1"
              />
              <el-option
                :label="$t('product.limitedTimeProd')"
                :value="2"
              />
              <el-option
                :label="$t('product.combinationGoods')"
                :value="5"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item
            prop="status"
            :label="$t('product.status') + ':'"
            class="search-form-item"
          >
            <el-select
              v-model="searchForm.status"
              clearable
              :placeholder="$t('product.status')"
            >
              <el-option
                :label="$t('publics.LowerShelf')"
                :value="0"
              />
              <el-option
                :label="$t('publics.UpperShelf')"
                :value="1"
              />
              <el-option
                :label="$t('product.violation')"
                :value="2"
              />
              <el-option
                :label="$t('product.violationPendingReview')"
                :value="3"
              />
              <el-option
                :label="$t('product.pendingReview')"
                :value="6"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="deliveryMode"
            :label="$t('product.delType') + ':'"
            class="search-form-item"
          >
            <el-select
              v-model="searchForm.deliveryMode"
              clearable
              :placeholder="$t('product.delType')"
            >
              <el-option
                :label="$t('product.userPickUp')"
                :value="2"
              />
              <el-option
                :label="$t('product.ExpressDistribution')"
                :value="1"
              />
              <el-option
                :label="$t('product.sameCityDelivery')"
                :value="4"
              />
              <el-option
                :label="$t('order.noNeedRequired')"
                :value="5"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="category"
            :label="$t('product.category')"
          >
            <el-tree-select
              v-model="searchForm.categoryId"
              :data="categoryList"
              :props="{
                value: 'categoryId',
                label: 'categoryName'
              }"
              check-strictly
            />
          </el-form-item>
          <!-- <el-form-item
            prop="isTop"
            :label="$t('product.isTop') + ':'"
            class="search-form-item"
          >
            <el-select
              v-model="isTop"
              clearable
              :placeholder="$t('product.isTop')"
            >
              <el-option
                :label="$t('publics.no')"
                :value="0"
              />
              <el-option
                :label="$t('publics.yes')"
                :value="1"
              />
            </el-select>
          </el-form-item> -->

          <el-form-item
            prop="selfProduct"
            label="是否自营:"
            class="search-form-item"
          >
            <el-select
              v-model="selfProduct"
              clearable
              placeholder="是否自营"
            >
              <el-option
                :label="$t('publics.no')"
                :value="0"
              />
              <el-option
                :label="$t('publics.yes')"
                :value="1"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="searchChange(true)"
            >
              {{ $t('product.search') }}
            </div>
            <div
              class="default-btn"
              @click="resetSearchForm()"
            >
              {{ $t('product.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="export-btn">
      <el-button
        v-if="isAuth('prod:prod:exportProd')"
        type="primary"
        @click="exportFrom()"
      >
        {{ $t('order.export') }}
      </el-button>
    </div>
    <div class="main-container">
      <div
        ref="closepopoverRef"
        class="table-con prod-table"
      >
        <el-table
          ref="prodListTable"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
          @selection-change="selectionChange"
          @sort-change="changeTableSort"
          @cell-mouse-enter="enterTableRow"
          @cell-mouse-leave="leaveTableRow"
        >
          <el-table-column
            type="selection"
            prop="prodId"
            width="55"
          />
          <el-table-column
            fixed
            prop="shopName"
            :label="$t('prodList.shopName')"
            width="165"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.shopName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed
            prop="prodName"
            :label="$t('group.prodInfo')"
            width="320"
          >
            <template #default="scope">
              <div class="table-cell-con">
                <div class="table-cell-image">
                  <ImgShow :src="scope.row.pic" />
                </div>
                <span class="table-cell-text">{{ scope.row.prodName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="oriPrice"
            :label="$t('prodList.marketValue')"
            width="100"
          >
            <template #default="scope">
              {{ moneyFormat(scope.row.oriPrice) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            :label="$t('prodList.salesPrice')"
            width="100"
          >
            <template #default="scope">
              {{ moneyFormat(scope.row.price) }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('product.waterSoldNum')"
            width="auto"
          >
            <template #default="scope">
              <div class="water-sold-con">
                <span>{{ scope.row.waterSoldNum }}</span>
                <el-popover
                  placement="bottom"
                  trigger="click"
                  :width="175"
                  @show="showWaterSoldNum(scope.row.waterSoldNum)"
                  @after-enter="getCurrentSpuId(scope.row.prodId, 'waterSoldNum')"
                  @hide="initProdInf()"
                >
                  <div class="popover-box">
                    <div>
                      <el-input-number
                        v-model="waterSoldNum"
                        type="number"
                        onkeypress="return( /[\d]/.test(String.fromCharCode(event.keyCode)))"
                        class="sales-volume"
                        :min="0"
                        :max="1000000000"
                        @change="(currentValue, oldValue) => {changeWaterSoldNum(currentValue, oldValue)}"
                      />
                    </div>
                    <div class="popover-bottom">
                      <el-button
                        @click="closePopover()"
                      >
                        取消
                      </el-button>
                      <el-button
                        type="primary"
                        @click="handleChange(scope.row.prodId)"
                      >
                        保存
                      </el-button>
                    </div>
                  </div>
                  <template #reference>
                    <el-icon
                      v-show="scope.row.prodId===currentMoveProdId || (scope.row.prodId===currentClickProdId && currentShowPopover==='waterSoldNum')"
                      class="el-icon-edit"
                    >
                      <EditPen />
                    </el-icon>
                  </template>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="totalStocks"
            :label="$t('product.availableInventory')"
            width="120"
          />
          <!-- 商品类型(0普通商品 1拼团 2秒杀 3积分 5活动商品) -->
          <!-- <el-table-column
            prop="prodType"
            :label="$t('product.prodType')"
            width="120"
          >
            <template #default="scope">
              商品类型(0普通商品 1拼团 2秒杀 3积分 5活动商品)
              <div class="tag-text">
                {{ [$t('product.ordProd'),$t('product.groupProd'),$t('product.limitedTimeProd'),$t('shopFeature.goods.points'),'', $t('product.combinationGoods')][scope.row.prodType] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="mold"
            :label="$t('product.prodMold')"
            width="120"
          >
            <template #default="scope">
              <div class="tag-text">
                {{ scope.row.mold === 0 ? $t('product.physicalGoods') : $t('product.virtualGoods') }}
              </div>
            </template>
          </el-table-column> -->
          <el-table-column
            prop="status"
            :label="$t('product.status')"
            width="auto"
          >
            <!-- 0:商家下架 1:正常 2:平台下架 3:违规下架待平台审核 4:审核失败 6:待审核 -1表示删除 -->
            <template #default="scope">
              <span
                v-if="scope.row.status === 1"
                class="tag-text"
              >{{ $t("prodList.onShelf") }}</span>
              <span
                v-else-if="scope.row.status === 0"
                class="tag-text"
              >{{ $t("prodList.offShelf") }}</span>
              <span
                v-else-if="scope.row.status === 2"
                class="tag-text"
              >{{ $t("product.violation") }}</span>
              <span
                v-else-if="scope.row.status === 3"
                class="tag-text"
              >{{ $t("product.violationPendingReview") }}</span>
              <span
                v-else-if="scope.row.status === 4"
                class="tag-text"
              >{{ $t("prodList.refusePass") }}</span>
              <span
                v-else-if="scope.row.status === 6"
                class="tag-text"
              >{{ $t("product.pendingReview") }}</span>
              <span
                v-else
                class="tag-text"
              >{{ $t("prodList.other") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="deliveryMode"
            align="center"
            :label="$t('product.delType')"
            width="100"
          >
            <template #default="scope">
              <div v-if="scope.row.mold === 1">
                {{ $t('order.noNeedRequired') }}
              </div>
              <div v-else-if="scope.row.prodType === 5">
                -
              </div>
              <div v-else>
                {{ DeliveryMode(scope.row.deliveryMode) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="selfProduct"
            label="自营"
            width="auto"
          >
            <template #default="scope">
              <span
                v-if="scope.row.selfProduct === 0"
                class="tag-text"
              >{{ $t('publics.no') }}</span>
              <span
                v-else-if="scope.row.selfProduct === 1"
                class="tag-text"
              >{{ $t('publics.yes') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="isTop"
            label="置顶"
            width="auto"
          >
            <template #default="scope">
              <span
                v-if="scope.row.isTop === 0"
                class="tag-text"
              >{{ $t('publics.no') }}</span>
              <span
                v-else-if="scope.row.isTop === 1"
                class="tag-text"
              >{{ $t('publics.yes') }}</span>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="280"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('prod:prod:update')"
                  class="default-btn text-btn"
                  @click="showProdInfo(scope.row.prodId)"
                >
                  {{ $t("prodList.lookOver") }}
                </div>

                <!-- <div
                  v-if="scope.row.selfProduct == 1 && isAuth('prod:prod:update')"
                  class="default-btn text-btn"
                  @click="onPrice(scope.row.prodId)"
                >
                  交易信息
                </div> -->

                <!-- 下架管理 违规下架待审核 -->
                <div
                  v-if="isAuth('prod:prod:update') && scope.row.status > 1 && scope.row.status !== 6"
                  class="default-btn text-btn"
                  @click="auditProdHandle(scope.row)"
                >
                  {{ scope.row.status === 2 ? $t("prodList.offShelfManage") : $t("product.violationPendingReview") }}
                </div>

                <!-- 待审核 -->
                <div
                  v-if="scope.row.status === 6"
                  class="default-btn text-btn"
                  @click="prodAuditHandle(scope.row)"
                >
                  {{ $t("product.pendingReview") }}
                </div>

                <!-- 违规下架 -->
                <div
                  v-if="isAuth('prod:prod:update') && scope.row.status < 2"
                  class="default-btn text-btn"
                  @click="offlineProdHandle(scope.row)"
                >
                  {{ $t("product.violation") }}
                  <el-tooltip
                    class="item"
                    effect="dark"
                    placement="right"
                    :content="$t('prodList.content')"
                  >
                    <el-icon><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>

                <div
                  v-if="isAuth('prod:prod:delete')"
                  class="default-btn text-btn"
                  @click="deleteHandle(scope.row.prodId)"
                >
                  {{ $t("remindPop.delete") }}
                </div>

                <div
                  v-if="scope.row.status === 1"
                  class="default-btn text-btn"
                  @click="toTopHandle(scope.row)"
                >
                  {{ scope.row.isTop === 1 ? $t('liveRoom.cancelTopping') : $t('publics.isTop') }}
                </div>

                <!-- <el-dropdown class="default-btn text-btn">
                  <div>更多</div>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item
                        v-if="isAuth('prod:prod:update') && scope.row.status > 1 && scope.row.status !== 6"
                        @click="auditProdHandle(scope.row)"
                      >
                        <div class="default-btn text-btn">
                          {{ scope.row.status === 2 ? $t("prodList.offShelfManage") : $t("product.violationPendingReview") }}
                        </div>
                      </el-dropdown-item>

                      <el-dropdown-item
                        v-if="scope.row.status === 6"
                        @click="prodAuditHandle(scope.row)"
                      >
                        <div class="default-btn text-btn">
                          {{ $t("product.pendingReview") }}
                        </div>
                      </el-dropdown-item>

                      <el-dropdown-item
                        v-if="isAuth('prod:prod:update') && scope.row.status < 2"
                        @click="offlineProdHandle(scope.row)"
                      >
                        <div class="default-btn text-btn">
                          {{ $t("product.violation") }}
                          <el-tooltip
                            class="item"
                            effect="dark"
                            placement="right"
                            :content="$t('prodList.content')"
                          >
                            <el-icon><QuestionFilled /></el-icon>
                          </el-tooltip>
                        </div>
                      </el-dropdown-item>

                      <el-dropdown-item
                        v-if="isAuth('prod:prod:delete')"
                        @click="deleteHandle(scope.row.prodId)"
                      >
                        <div class="default-btn text-btn">
                          {{ $t("remindPop.delete") }}
                        </div>
                      </el-dropdown-item>

                      <el-dropdown-item
                        v-if="scope.row.status === 1"
                        @click="toTopHandle(scope.row)"
                      >
                        <div class="default-btn text-btn">
                          {{ scope.row.isTop === 1 ? $t('liveRoom.cancelTopping') : $t('publics.isTop') }}
                        </div>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown> -->
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品审核弹窗 -->
    <offline-audit
      v-if="ProdOfflineAuditVisible"
      ref="ProdOfflineAuditRef"
      select-url="/prod/prod/getOfflineHandleEventByProdId"
      update-url="/prod/prod/prodOfflineAudit"
      @refresh-data-list="refreshChange"
    />
    <prod-audit
      v-if="prodAuditVisible"
      ref="auditProdRef"
      update-url="/prod/prod/auditProd"
      @refresh-data-list="refreshChange"
    />
    <!-- 商品详情弹窗 -->
    <el-dialog
      v-model="showProdInfoDialog"
      :title="$t('prodList.detailsTitle')"
      width="70%"
      class="prod-detail-dialog"
    >
      <div class="prod-row">
        <span class="row-title">{{ $t("product.platformClassification") + ':' }}</span>
        <span class="row-txt">
          <span
            v-for="(itemCategory, indexCategory) in prodInfoCategory"
            :key="indexCategory"
          >{{ itemCategory + (indexCategory < (prodInfoCategory.length - 1) ? ' > ' : '') }}</span>
        </span>
      </div>
      <div class="prod-row">
        <span class="row-title">{{ $t("product.prodName") + ':' }}</span>
        <span class="row-txt">{{ prodInfo.prodName }}</span>
      </div>
      <div class="prod-row">
        <span class="row-title">{{ $t("prodList.sellingPoints") + ':' }}</span>
        <span class="row-txt">{{ prodInfo.brief===''?'-':prodInfo.brief }}</span>
      </div>
      <div class="prod-row">
        <span class="row-title inline-block">{{ $t("product.pic") + ':' }}</span>
        <div class="flex-box-img">
          <span
            v-for="(item,index) in prodInfo.imgs"
            :key="index"
            class="detail-prod"
          >
            <ImgShow
              :src="item"
              :class-list="['prod-img']"
            />
          </span>
        </div>
      </div>
      <div
        v-if="prodInfo.prodParameterList && prodInfo.prodParameterList.length > 0"
        class="prod-row"
      >
        <span class="row-title">{{ $t('prodList.parameters') }}:</span>
        <span class="row-txt params-box">
          <span
            v-for="(item,index) in prodInfo.prodParameterList"
            :key="index"
            class="prod-params"
          >
            <span>{{ item.parameterKey }}:</span>
            <span>{{ item.parameterValue }}</span>
          </span>
        </span>
      </div>
      <div class="main-container">
        <div class="table-con table-box">
          <span class="row-title">{{ $t("prodList.specs") + ':' }}</span>
          <!-- 规格表格 -->
          <el-table
            :data="prodInfo.skuList"
            header-cell-class-name="table-header"
            row-class-name="table-row"
            class="table"
            style="width: 100%"
          >
            <el-table-column
              fixed
              prop="prodName"
              width="240"
              :label="$t('product.prodName')"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.prodName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="partyCode"
              width="150"
              label="商品型号"
              show-overflow-tooltip
            />

            <el-table-column
              prop="properties"
              :label="$t('prodList.attribute')"
              width="240"
            >
              <template #default="scope">
                <p
                  v-if="scope.row.properties"
                  class="table-cell-text"
                >
                  {{ scope.row.properties }}
                </p>
                <p
                  v-else
                  class="table-cell-text"
                >
                  {{ $t("prodList.noAttribute") }}
                </p>
              </template>
            </el-table-column>
            <el-table-column
              prop="pic"
              :label="$t('product.pic')"
            >
              <template #default="scope">
                <img
                  v-if="scope.row.pic"
                  :key="scope.row.skuId"
                  :src="checkFileUrl(scope.row.pic)"
                  class="tab-img"
                >
                <img
                  v-else
                  :src="checkFileUrl(prodInfo.imgs[0])"
                  class="tab-img"
                >
              </template>
            </el-table-column>

            <el-table-column
              prop="price"
              :label="$t('prodList.salesPrice')"
            >
              <template #default="scope">
                {{ moneyFormat(scope.row.price) }}
              </template>
            </el-table-column>

            <el-table-column
              prop="oriPrice"
              :label="$t('prodList.marketValue')"
            >
              <template #default="scope">
                {{ moneyFormat(scope.row.oriPrice) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="stocks"
              :label="$t('product.totalStocks')"
            />
            <el-table-column
              v-if="prodInfo.mold===0"
              prop="weight"
              :label="$t('prodList.prodWeight')"
            />
            <el-table-column
              v-if="prodInfo.mold===0"
              prop="volume"
              :label="$t('prodList.prodVolume')"
            />
          </el-table>
        </div>
      </div>
      <template #footer>
        <span
          class="dialog-footer"
        >
          <div
            class="default-btn primary-btn"
            @click="showProdInfoDialog = false"
          >{{
            $t("remindPop.confirm")
          }}</div>
        </span>
      </template>
    </el-dialog>

    <!-- 违规下架弹窗 -->
    <el-dialog
      v-model="offlineProdDialog"
      title="提示"
      width="500px"
      left
      class="offline-dialog"
      :close-on-click-modal="false"
      top="25vh"
    >
      <div class="offline-title">
        <span>{{ $t('remindPop.determine') + $t('remindPop.prod') + ` [${offlineProdInfo.prodName}] ` + $t('remindPop.offshelf') + $t('remindPop.reason') }}</span>
      </div>
      <el-input
        v-model.trim="offlineReason"
        type="textarea"
        :autosize="{ minRows: 3, maxRows: 6}"
        maxlength="500"
        :placeholder="$t('product.reasonRemoval')"
        show-word-limit
        :class="{'reasonEmpty':isReasonEmpty}"
        @focus="isReasonEmpty = false"
        @blur="isReasonEmpty = offlineReason===''"
      />
      <div class="offline-reason-hint">
        <span v-show="isReasonEmpty">{{ $t('remindPop.emptyReason') }}</span>
      </div>
      <template #footer>
        <span>
          <el-button
            @click="offlineProdDialog = false"
          >{{ $t('remindPop.cancel') }}</el-button>
          <el-button
            type="primary"
            @click="submitOfflineProd()"
          >{{ $t('remindPop.confirm') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { isAuth } from '@/utils'

const Data = reactive({
  tempSearchForm: null, // 保存上次点击查询的请求条件
  theParams: null, // 保存上次点击查询的请求条件
  dataForm: {
    prodName: ''
  },
  dataList: [],
  page: {
    total: 0, // 总页数
    currentPage: 1, // 当前页数
    pageSize: 10 // 每页显示多少条
  },
  searchForm: {
    shopName: '',
    keyword: '',
    status: '',
    deliveryMode: '',
    categoryId: ''
  },
  dataListSelections: [],
  currentMoveProdId: '', // 移入项的spuId
  currentClickProdId: '', // 点击项的spuId
  currentShowPopover: '', // 当前展示的弹窗
  waterSoldNum: null,
  dataListLoading: false,
  showProdInfoDialog: false,
  ProdOfflineAuditVisible: false,
  prodAuditVisible: false,
  prodName: '',
  prodNameRouter: '',
  prodId: null,
  // 0无 1.排序号排序
  sortParam: 0,
  selfProduct: null,
  // 0无 1 正序 2倒序
  sortType: 0,
  prodInfo: {},
  skuList: [],
  waterArr: [],
  categoryId: null,
  // 分类list
  categoryList: [],
  prodInfoCategory: [], // 商品详情分类
  prodListExport: [],
  // 违规下架相关
  offlineProdDialog: false, // 弹窗显隐
  offlineReason: '', // 下架原因
  offlineProdInfo: {}, // 所选下架商品的信息
  isReasonEmpty: false // 原因字段为空的提示显隐
})

const { dataList, page, searchForm, currentMoveProdId, currentClickProdId, currentShowPopover, waterSoldNum, showProdInfoDialog, ProdOfflineAuditVisible, prodAuditVisible, selfProduct, prodInfo, categoryList, prodInfoCategory, offlineProdDialog, offlineReason, offlineProdInfo, isReasonEmpty } = toRefs(Data)

const route = useRoute()
onMounted(() => {
  if (route.query.prodName) {
    Data.prodNameRouter = route.query.prodName
    Data.prodName = route.query.prodName
  }
  Data.prodId = route.query.prodId ? route.query.prodId : null
  const parPage = useRoute().query.page
  const search = useRoute().query.search
  if (search) {
    Object.assign(Data.searchForm, JSON.parse(decodeURI(search)))
  }
  if (parPage) {
    const { total, currentPage, pageSize } = JSON.parse(decodeURI(parPage))
    Data.page.total = total
    Data.page.currentPage = currentPage
    Data.page.pageSize = pageSize
  }

  getDataList(Data.page)
  // 获取平台分类
  getCategoryList()
})

const DeliveryMode = (value) => {
  // 将商品的配送方式字符串转化为json
  const objValue = JSON.parse(value)
  // 声明返回结果 result
  const result = []
  if (objValue.hasCityDelivery === true) {
    result.push($t('product.sameCityDelivery'))
  }
  if (objValue.hasUserPickUp === true) {
    result.push($t('product.userPickUp'))
  }
  if (objValue.hasShopDelivery === true) {
    result.push($t('product.ExpressDistribution'))
  }
  return result.join(' / ')
}

// 获取数据列表
const getDataList = (page, sort, newData = false) => {
  Data.dataListLoading = true
  if (newData || !Data.tempSearchForm) {
    Data.theParams = JSON.parse(JSON.stringify(Data.searchForm))
    Data.tempSearchForm = {
      current: page == null ? Data.page.currentPage : page.currentPage,
      keyword: Data.prodNameRouter ? Data.prodNameRouter : Data.prodName,
      prodId: Data.prodId ? Data.prodId : null,
      size: page == null ? Data.page.pageSize : page.pageSize,
      selfProduct: Data.selfProduct,
      categoryId: Data.categoryId,
      mustNotProdTypes: !Data.searchForm.prodType ? [3] : null
    }
  } else {
    Data.tempSearchForm.current = page == null ? Data.page.currentPage : page.currentPage
    Data.tempSearchForm.size = page == null ? Data.page.pageSize : page.pageSize
  }
  if (sort) {
    Data.theParams.sort = sort === 'ascending' ? 13 : 12
  } else {
    Data.theParams.sort = null
  }
  if (Data.searchForm.deliveryMode) {
    if (Data.searchForm.deliveryMode === 5) {
      Data.theParams.deliveryMode = null
      if (Data.searchForm.mold === 0) {
        // 实物商品
        Data.dataList = []
        return
      }
      // 无需快递
      if (Data.searchForm.mold == null || Data.searchForm.mold === '') {
        Data.theParams.mold = 1
      }
    } else {
      // 实物快递
      if (Data.searchForm.mold === 1) {
        // 虚拟商品
        Data.dataList = []
        return
      }
      Data.theParams.mold = 0
      if (Data.tempSearchForm.mustNotProdTypes && Data.tempSearchForm.mustNotProdTypes.length >= 0) {
        Data.tempSearchForm.mustNotProdTypes.push(5)
      } else {
        Data.tempSearchForm.mustNotProdTypes = [5]
      }
    }
  }
  http({
    url: http.adornUrl('/platform/search/prod/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        Data.tempSearchForm,
        Data.theParams
      )
    )
  }).then(({ data }) => {
    // Data.page = page
    Data.dataList = data.records
    // console.log('00', Data.dataList)
    for (const key in Data.dataList) {
      // eslint-disable-next-line no-prototype-builtins
      if (Data.dataList.hasOwnProperty(key)) {
        const element = Data.dataList[key]
        element.imgs = element.pic
      }
    }
    Data.prodName = ''
    Data.prodNameRouter = null
    Data.page.total = data.total
    Data.dataListLoading = false

    // 末尾页数据为空重新请求
    if (!Data.dataList.length && Data.page.currentPage > 1) {
      Data.page.currentPage = 1
      getDataList()
    }
  })
}

const changeTableSort = (column) => {
  getDataList(Data.page, column.order)
}

// 获取平台分类列表
const getCategoryList = () => {
  Data.dataListLoading = true
  http({
    url: http.adornUrl('/prod/category/listCategoryByGrade'),
    method: 'get',
    params: http.adornParams({
      grade: 2
    })
  }).then(({ data }) => {
    Data.categoryList = treeDataTranslate(data, 'categoryId', 'parentId')
    Data.dataListLoading = false
  })
}

// 获取商品详情
const showProdInfo = (id) => {
  Data.showProdInfoDialog = true
  http({
    url: http.adornUrl(`/prod/prod/info/${id}`),
    method: 'GET'
  }).then(res => {
    res.data.imgs = res.data.imgs ? res.data.imgs.split(',') : []
    Data.prodInfo = res.data
    Data.skuList = res.data.skuList
    showProdCategory(res.data.categoryId)
  })
}

const showProdCategory = (id) => {
  http({
    url: http.adornUrl('/prod/category/getCategoryAndParent'),
    params: {
      categoryId: id
    },
    method: 'GET'
  }).then(res => {
    Data.prodInfoCategory = []
    res.data.forEach(item => {
      Data.prodInfoCategory.push(item.categoryName)
    })
  })
}

const showWaterSoldNum = (val) => {
  Data.waterSoldNum = val
}

const changeWaterSoldNum = (currentValue) => {
  Data.waterSoldNum = currentValue
}

// 更改注水销量
const handleChange = (id) => {
  let waterSoldNum = Math.round(Data.waterSoldNum)
  if (waterSoldNum > 1000000000) {
    waterSoldNum = 1000000000
  }
  if (!waterSoldNum && waterSoldNum !== 0) {
    ElMessage({
      message: $t('tip.input') + $t('product.waterSoldNum'),
      type: 'error',
      duration: 1500
    })
    return
  }
  http({
    url: http.adornUrl('/prod/prod/waterSoldNum'),
    method: 'put',
    params: {
      waterSoldNum,
      prodId: id
    }
  }).then(() => {
    ElMessage({
      message: $t('remindPop.success'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        getDataList(Data.page)
        closePopover()
      }
    })
  })
}

// 删除
const deleteHandle = (id) => {
  ElMessageBox.confirm($t('remindPop.makeSure') + ' ' + `[${id ? $t('remindPop.delete') : $t('remindPop.batchDeletion')}]` + ' ' + $t('remindPop.operation') + '?', $t('remindPop.remind'), {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl(`/prod/prod/${id}`),
        method: 'delete',
        data: http.adornData({})
      }).then(() => {
        ElMessage({
          message: $t('remindPop.succeeded'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            getDataList(Data.page)
          }
        })
      })
    })
    .catch(() => {

    })
}

// 提交商品下架原因
const submitOfflineProd = Debounce(() => {
  if (Data.offlineReason === '') {
    Data.isReasonEmpty = true
    return
  }
  Data.offlineProdDialog = false
  http({
    url: http.adornUrl('/prod/prod/offline'),
    method: 'post',
    data: http.adornData({
      handleId: Data.offlineProdInfo.prodId,
      offlineReason: Data.offlineReason || null
    })
  }).then(() => {
    ElMessage({
      message: $t('remindPop.succeeded'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        getDataList(Data.page)
      }
    })
  })
}, 1500)

// 下架
const offlineProdHandle = (row) => {
  Data.offlineProdInfo = row
  Data.offlineReason = ''
  Data.offlineProdDialog = true
  Data.isReasonEmpty = false
}

// 条件查询
const searchChange = (newData = false) => {
  Data.page.currentPage = 1
  getDataList(Data.page, false, newData)
}

const toTopHandle = (row) => {
  let str = $t('publics.isTop')
  if (row.isTop === 1) {
    str = $t('liveRoom.cancelTopping')
  }
  ElMessageBox.confirm($t('remindPop.makeSure') + ' ' + str + ' ' + $t('remindPop.operation') + '?', $t('remindPop.remind'), {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/prod/prod/toTop/' + row.prodId),
      method: 'put',
      data: http.adornData({})
    }).then(() => {
      ElMessage({
        message: $t('remindPop.succeeded'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          refreshChange()
        }
      })
    })
  }).catch(() => { })
}

// 获取弹出弹窗项信息
const getCurrentSpuId = (spuId, currentShowPopover) => {
  Data.currentClickProdId = spuId
  Data.currentShowPopover = currentShowPopover
}

// 清空选中项弹窗信息
const clearShowPopoverInf = () => {
  Data.currentClickProdId = ''
  Data.currentShowPopover = ''
}

// 关闭弹窗后,初始化数据
const initProdInf = () => {
  // row.waterSoldNum = row.waterSoldNum
  clearShowPopoverInf()
}

const closepopoverRef = ref()
// 关闭popover弹窗
const closePopover = () => {
  closepopoverRef.value.click()
}

// 移入表格行
const enterTableRow = (row) => {
  Data.currentMoveProdId = row.prodId
}

// 移出表格行
const leaveTableRow = () => {
  Data.currentMoveProdId = ''
}

// 多选变化
const selectionChange = (val) => {
  Data.dataListSelections = val
}

// 导出
const exportFrom = () => {
  const params = {
    prodIds: Data.dataListSelections.map(x => x.prodId)
  }
  const loading = ElLoading.service({
    lock: true,
    target: '.prod-list-mod',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('shop.exportIng')
  })
  http({
    url: http.adornUrl('/platform/search/prod/prodExport'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        Data.tempSearchForm,
        Data.theParams,
        params
      )
    ),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('shopFeature.allCanUse.goodsList') + '.xlsx'

    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  }).catch((e) => {
    loading.close()
  })
}

const ProdOfflineAuditRef = ref()
// 违规下架的商品审核
const auditProdHandle = (row) => {
  Data.ProdOfflineAuditVisible = true
  nextTick(() => {
    ProdOfflineAuditRef.value.init(row.prodId)
  })
}

const auditProdRef = ref()
// 待审核的商品审核
const prodAuditHandle = (row) => {
  Data.prodAuditVisible = true
  nextTick(() => {
    auditProdRef.value.init(row.prodId)
  })
}

// 刷新商品
const refreshChange = () => {
  getDataList(Data.page)
}

const router = useRouter()
/**
 * 重置表单
 */
const resetSearchForm = () => {
  Data.searchForm = {
    shopName: '',
    keyword: '',
    status: '',
    deliveryMode: '',
    categoryId: ''
  }
  router.push('/prod/prod-list/index')
  Data.prodId = null
  Data.selfProduct = null
}

const handleSizeChange = (val) => {
  Data.page.pageSize = val
  getDataList()
}

const handleCurrentChange = (val) => {
  Data.page.currentPage = val
  getDataList()
}

const onPrice = (id) => {
  http({
    url: http.adornUrl(`/prod/prod/info/${id}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data.modelType == 1) {
      ElMessage.warning('选型模式暂不支持')
      // router.push({
      //   path: '/prod/manage/sprice',
      //   query: { prodId: id, page: encodeURI(JSON.stringify(page)), search: encodeURI(JSON.stringify(searchForm)) }
      // })
    } else if (data.modelType === 0 || data.modelType === 3) {
      router.push({
        path: '/prod/prod-list/price',
        query: { prodId: id, shopId: data.shopId, page: encodeURI(JSON.stringify(Data.page)), search: encodeURI(JSON.stringify(Data.searchForm)) }
      })
    } else {
      ElMessage.warning('该商品尚未配置规格')
    }
  })
}

</script>

<style scoped lang="scss">
@use "index";
</style>
